package fnic.prehand.common;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import fnic.jsontrans.ProbeAddress;

public class PbAddrMapService {
	private static final Logger LOG = Logger.getLogger(PbAddrMapService.class);
	private static AgentConfig config = AgentConfig.getInstance();
	private static final HttpMsgService httpInstance = HttpMsgService.getInstance();
	private static final JacksonFormatService jsonInstance = JacksonFormatService.getInstance();
	private static final int mapSize = config.getPbAddrMapSize();
	
	private final String probeAddrUrl;
	private Map<Integer, ProbeAddress> hashmap = new HashMap<Integer, ProbeAddress>(mapSize);

	public PbAddrMapService(String url){
		probeAddrUrl = url;
	}
	
	/*
	 * 判断MAP已满
	 */
	private synchronized boolean isMapFull() {
		return (hashmap.size() == mapSize);
	}

	/*
	 * 添加Item
	 */
	private synchronized boolean putItem(int probeid, ProbeAddress item) {
		if (!isMapFull()) {
			hashmap.put(probeid, item);
			return true;
		} else {
			LOG.error("Probe Address HashMap full");
			return false;
		}
	}
	
	/*
	 * 判断是否存在Item
	 */
	private boolean containItem(int probeid){
		return hashmap.containsKey(probeid);
	}
	
	/*
	 * 获取Item
	 */
	private ProbeAddress localMapAddr(int probeid){
		ProbeAddress addr = null;
		if(hashmap.containsKey(probeid)){
			addr = hashmap.get(probeid);
		}
		return addr;
	}
	
	/*
	 * 通过管理节点获取探针的位置，省市区信息 
	 */
	private ProbeAddress httpPbAdres(int probeId)
	{
		ProbeAddress address = null;
		String adrs = probeAddrUrl+probeId; // 追加probeid
		StringBuilder rspbuilder = new StringBuilder();
		
		//向管理节点发送http消息获得sk timeout
		boolean succeedFg = httpInstance.sendGetMsg(true, adrs, rspbuilder);
		if(succeedFg){
			if(rspbuilder.length()>0){
				String httprsp = rspbuilder.toString(); //验证一下是否为json格式
				address = (ProbeAddress)jsonInstance.String2Obj(httprsp, "fnic.jsontrans.ProbeAddress");
			}
			else{
				LOG.error("[getPbAdres]Get Http Rsp length is zero !!");
			}
		}else{
			LOG.error("[getPbAdres]Get Http Rsp Code error!!");
		}
		return address;
	}
	
	public ProbeAddress getProbeAddr(int probeId) {
		// 获取地区信息，本地获取不成功到管理节点获取
		ProbeAddress pbaddr = null;
		if (containItem(probeId)) {
			pbaddr = localMapAddr(probeId);
		} else {
			pbaddr = httpPbAdres(probeId);
			if (pbaddr != null) {
				putItem(probeId, pbaddr);
			}else{
				return null;
			}
		}
		return pbaddr;
	}
}
